const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const serve = require('koa-static');
const log4js = require('log4js');

// 日志配置
log4js.configure({
    appenders: {
        out: { type: 'console' },
        app: { type: 'file', filename: 'logs/app.log', maxLogSize: 10485760, backups: 3, compress: true }
    },
    categories: {
        default: { appenders: ['out', 'app'], level: 'info' }
    }
});
const logger = log4js.getLogger();

const app = new Koa();
const router = new Router();
const crawlerRouter = require('./routes/crawler');
const db = require('./db');

// 启动时自动检查并创建用户表
(async () => {
    try {
        await db.initUserTable();
        logger.info('用户表已检查/创建');
    } catch (err) {
        logger.error('用户表初始化失败:', err);
    }
})();

// 日志中间件，记录每个请求
app.use(async (ctx, next) => {
    logger.info(`${ctx.method} ${ctx.url}`);
    try {
        await next();
    } catch (err) {
        logger.error('请求出错:', err);
        throw err;
    }
});

// 解析请求体
app.use(bodyParser());
// 静态资源（可选）
app.use(serve(__dirname + '/public'));

// 路由
app.use(router.routes()).use(router.allowedMethods());
app.use(crawlerRouter.routes()).use(crawlerRouter.allowedMethods());

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    logger.info(`Koa2 server running at http://localhost:${PORT}`);
    console.log(`Koa2 server running at http://localhost:${PORT}`);
});
